<?php

namespace app\api\service;

use app\common\service\ConfigService;
use app\model\User;
use EasyWeChat\Factory;
use think\facade\Cache;

/**
 * @desc 微信小程序
 * Class WechatappService
 * @package app\api\service.
 */
class WechatappService extends CommonService
{
    protected static $wxapp;

    public static function getApp()
    {
        if (empty(self::$wxapp))
        {
            $sysConfig = ConfigService::getConf('sys_wechatapp', 'admin');
            $config = [
                'app_id' => $sysConfig['appid'],
                'secret' => $sysConfig['key'],

                // 下面为可选项
                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array',

                'log' => [
                    'level' => 'debug',
                    'file' => __DIR__.'/wechat.log',
                ],
            ];
            self::$wxapp = Factory::miniProgram($config);
        }
        return self::$wxapp;
    }

    /**
     * @desc 获取用户授权的openid和session_key
     * @param $code
     * @return mixed
     * @throws \app\common\exception\HttpCode
     */
    public static function session($code)
    {
        if (empty($code))
        {
            self::error(400);
        }

        $result = self::$wxapp->auth->session($code);

        if (empty($result['openid']) || empty($result['session_key']))
        {
            self::error(401);
        }

        $cacheKey = 'session_key' . $result['openid'];
        Cache::set($cacheKey, $result['session_key']);
        return $result;
    }

    /**
     * @desc 用户登录
     * @param $request
     * @return bool|string
     * @throws \app\common\exception\HttpCode
     */
    public static function login($request)
    {
        $userinfo = json_decode($request['userInfo'], true);
        $openid = $request['openid'];
        $user = self::getUser($userinfo, $openid);

        if (empty($user))
        {
            self::error(400);
        }

        // 获取用户token返回前端用于登录
        $token = php_encrypt($user['id'], 'E', 32, 86400);
        return $token;
    }

    /**
     * @desc 根据openid获取用户信息,没有就插入
     * @param $userinfo
     * @param $openid
     * @return array
     */
    private static function getUser($userinfo, $openid)
    {
        $user = User::getOne(['openid' => $openid]);
        if (empty($user))
        {
            $userData['pid'] = 0;
            $userData['nickname'] = $userinfo['nickName'];
            $userData['openid'] = $openid;
            $userData['avatar'] = $userinfo['avatarUrl'];
            $userData['from'] = 1;
            $userData['sex'] = $userinfo['gender'];
            $userData['mobile'] = 0;
            $userData['wechat'] = '';
            $userData['integral'] = 0;
            $userData['province'] = $userinfo['province'];
            $userData['city'] = $userinfo['city'];
            $userData['district'] = '';
            $userData['confirm'] = 0;
            $userData['last_login_time'] = time();
            $userData['create_time'] = time();
            $userData['update_time'] = time();
            User::addOne($userData);
            $user = User::getOne(['openid' => $openid]);
        } else {
            $userData['last_login_time'] = time();
            User::updateOne($userData, ['id' => $user['id']]);
        }
        return $user;
    }
}